package com.serverTechnology.teamsGroups.service.impl;

import com.serverTechnology.teamsGroups.constants.FixedNames;
import com.serverTechnology.teamsGroups.entity.TeStepsDrawing;
import com.serverTechnology.teamsGroups.entity.dto.StepsDrawingDto;
import com.serverTechnology.teamsGroups.mapper.TeStepsDrawingMapper;
import com.serverTechnology.teamsGroups.service.ITeStepsDrawingService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.Base64;
import java.util.UUID;

/**
 * <p>
 * 工步所需图纸 服务实现类
 * </p>
 *
 * @author 王凯炫
 * @since 2024-08-01
 */
@Service
public class TeStepsDrawingServiceImpl extends ServiceImpl<TeStepsDrawingMapper, TeStepsDrawing> implements ITeStepsDrawingService {

    @Value("${file.upload-dir:D:/a/}")
    private String uploadDir;

    @Override
    public void addDrawing(StepsDrawingDto stepsDrawingDto) {
        String base64File = stepsDrawingDto.getFile();
        byte[] fileBytes = Base64.getDecoder().decode(base64File);

        // 生成唯一文件名
        // 根据需要生成或指定文件名
        String fileName = stepsDrawingDto.getFileName();
        UUID uuid = UUID.nameUUIDFromBytes(fileName.getBytes());

        try {
            File addFile = new File(uploadDir + uuid.toString() + "//" + fileName);
            if (!addFile.getParentFile().exists()) {
                addFile.getParentFile().mkdirs();
            }
            Files.write(addFile.toPath(), fileBytes);

            // 保存文件信息到数据库
            TeStepsDrawing teStepsDrawing = new TeStepsDrawing();
            teStepsDrawing.setStepsId(stepsDrawingDto.getStepsId());
            teStepsDrawing.setDrawingName(fileName);
            teStepsDrawing.setImage(uuid.toString() + "//" + fileName);
            this.save(teStepsDrawing);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

//    @Override
//    public void addDrawing(MultipartFile file, StepsDrawingDto stepsDrawingDto) {
//        if(!file.getContentType().equals(FixedNames.PDF)){
//            throw new RuntimeException("文件格式错误");
//        }
//        //获取文件名称
//        String fileName = file.getOriginalFilename();
//        //生成唯一文件名
//        UUID uuid = UUID.nameUUIDFromBytes(fileName.getBytes());
//
//        try {
//            File addFile = new File(uploadDir + uuid.toString() + "//" + fileName);
//            //当父级目录不存在时，自动创建
//            if (!addFile.getParentFile().exists()) {
//                addFile.getParentFile().mkdirs();
//            }
//            //存储文件到电脑磁盘
//            file.transferTo(addFile);
//            //存储文件到数据库
//            TeStepsDrawing teStepsDrawing = new TeStepsDrawing();
//            teStepsDrawing.setStepsId(stepsDrawingDto.getStepsId());
//            teStepsDrawing.setDrawingName(fileName);
//            teStepsDrawing.setImage(uuid.toString() + "//" + fileName);
//            //保存
//            this.save(teStepsDrawing);
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//
//
//    }

    /**
     * 查询要下载的工步所需图纸
     *
     * @param id
     * @return
     */
    @Override
    public void pageDrawing(Long id, HttpServletResponse response) {
        TeStepsDrawing teStepsDrawing = this.getById(id);
        //  新建文件流，从磁盘读取文件流
        try (
                FileInputStream fis = new FileInputStream(uploadDir + teStepsDrawing.getImage());
                BufferedInputStream bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream()) {    //  OutputStream 是文件写出流，讲文件下载到浏览器客户端
            // 新建字节数组，长度是文件的大小，比如文件 6kb, bis.available() = 1024 * 6
            byte[] bytes = new byte[bis.available()];
            // 从文件流读取字节到字节数组中
            bis.read(bytes);
            // 重置 responsel
            response.reset();
            // 设置 response 的下载响应头
            response.setContentType("application/pdf");
            response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(teStepsDrawing.getImage(), "UTF-8"));  // 注意，这里要设置文件名的编码，否则中文的文件名下载后不显示
            // 写出字节数组到输出流
            os.write(bytes);
            // 刷新输出流
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
